package org.example.Agricultural_33.controller;

import org.example.Agricultural_33.model.CommonResponse;
import org.example.Agricultural_33.model.ProductDTO;
import org.example.Agricultural_33.model.ProductRequest;
import org.example.Agricultural_33.model.bo.*;
import org.example.Agricultural_33.service.AgriculturalTraceabilityService;
import org.fisco.bcos.sdk.transaction.model.dto.CallResponse;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 农产品控制器
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    private AgriculturalTraceabilityService agriculturalTraceabilityService;

    /**
     * 创建新产品
     * @param request 产品请求
     * @return 创建结果
     */
    @PostMapping
    public CommonResponse createProduct(@RequestBody ProductRequest request) {
        try {
            System.out.println("创建产品请求: " + request);
            System.out.println("生产日期: " + request.getProductionDate() + ", 类型: " + 
                (request.getProductionDate() != null ? request.getProductionDate().getClass().getName() : "null"));
            
            AgriculturalTraceabilityCreateProductInputBO inputBO = new AgriculturalTraceabilityCreateProductInputBO();
            inputBO.set_id(request.getId());
            inputBO.set_name(request.getName());
            inputBO.set_producer(request.getProducer());
            
            // 处理productionDate
            BigInteger productionDate = request.getProductionDate();
            if (productionDate == null && request.getProductionDateStr() != null) {
                try {
                    // 尝试从字符串转换
                    System.out.println("尝试从字符串转换日期: " + request.getProductionDateStr());
                    productionDate = new BigInteger(request.getProductionDateStr());
                    System.out.println("转换后的日期时间戳: " + productionDate);
                } catch (Exception e) {
                    System.err.println("从字符串转换生产日期失败: " + e.getMessage());
                    // 使用当前时间作为默认值
                    productionDate = BigInteger.valueOf(System.currentTimeMillis() / 1000);
                    System.err.println("使用当前时间作为默认值: " + productionDate);
                }
            }
            
            // 确保日期是秒级时间戳，BigInteger太大可能是毫秒级
            if (productionDate != null && productionDate.compareTo(BigInteger.valueOf(10000000000L)) > 0) {
                System.out.println("检测到毫秒级时间戳，转换为秒级: " + productionDate);
                productionDate = productionDate.divide(BigInteger.valueOf(1000));
                System.out.println("转换后的秒级时间戳: " + productionDate);
            }
            
            inputBO.set_productionDate(productionDate);
            inputBO.set_origin(request.getOrigin());
            
            System.out.println("最终产品信息: ID=" + request.getId() + 
                              ", 名称=" + request.getName() + 
                              ", 生产商=" + request.getProducer() + 
                              ", 生产日期=" + productionDate + 
                              ", 原产地=" + request.getOrigin());
            
            TransactionResponse response = agriculturalTraceabilityService.createProduct(inputBO);
            System.out.println("产品创建成功: " + request.getId());
            return CommonResponse.ok(response);
        } catch (Exception e) {
            System.err.println("产品创建失败: " + e.getMessage());
            e.printStackTrace();
            return CommonResponse.fail("F001", e);
        }
    }

    /**
     * 获取产品详情
     * @param id 产品ID
     * @return 产品信息
     */
    @GetMapping("/{id}")
    public CommonResponse getProduct(@PathVariable String id) {
        try {
            System.out.println("获取产品详情请求: " + id);
            AgriculturalTraceabilityGetProductInputBO inputBO = new AgriculturalTraceabilityGetProductInputBO();
            inputBO.set_id(id);
            
            CallResponse response = agriculturalTraceabilityService.getProduct(inputBO);
            System.out.println("产品响应原始数据: " + response.getReturnObject());
            
            if (response.getReturnObject() instanceof List) {
                List<Object> productInfo = (List<Object>) response.getReturnObject();
                if (productInfo.size() >= 7) {  // 确保至少有7个元素，对应基本字段
                    ProductDTO productDTO = new ProductDTO();
                    productDTO.setId(id);
                    
                    // 安全地设置各个字段，处理可能的类型转换
                    try {
                        // 设置name
                        if (productInfo.get(0) != null) {
                            if (productInfo.get(0) instanceof String) {
                                productDTO.setName((String) productInfo.get(0));
                            } else if (productInfo.get(0) instanceof List) {
                                productDTO.setName(String.join(", ", (List<String>) productInfo.get(0)));
                            } else {
                                productDTO.setName(productInfo.get(0).toString());
                            }
                        } else {
                            productDTO.setName(id);
                        }
                        
                        // 设置producer
                        if (productInfo.get(1) != null) {
                            if (productInfo.get(1) instanceof String) {
                                productDTO.setProducer((String) productInfo.get(1));
                            } else if (productInfo.get(1) instanceof List) {
                                productDTO.setProducer(String.join(", ", (List<String>) productInfo.get(1)));
                            } else {
                                productDTO.setProducer(productInfo.get(1).toString());
                            }
                        } else {
                            productDTO.setProducer("未知");
                        }
                        
                        // 设置origin
                        if (productInfo.get(2) != null) {
                            if (productInfo.get(2) instanceof String) {
                                productDTO.setOrigin((String) productInfo.get(2));
                            } else if (productInfo.get(2) instanceof List) {
                                productDTO.setOrigin(String.join(", ", (List<String>) productInfo.get(2)));
                            } else {
                                productDTO.setOrigin(productInfo.get(2).toString());
                            }
                        } else {
                            productDTO.setOrigin("未知");
                        }
                        
                        // 设置productionDate
                        if (productInfo.get(3) != null) {
                            if (productInfo.get(3) instanceof BigInteger) {
                                productDTO.setProductionDate((BigInteger) productInfo.get(3));
                            } else if (productInfo.get(3) instanceof String) {
                                try {
                                    productDTO.setProductionDate(new BigInteger((String) productInfo.get(3)));
                                } catch (NumberFormatException e) {
                                    productDTO.setProductionDate(BigInteger.valueOf(System.currentTimeMillis() / 1000));
                                }
                            } else {
                                productDTO.setProductionDate(BigInteger.valueOf(System.currentTimeMillis() / 1000));
                            }
                        } else {
                            productDTO.setProductionDate(BigInteger.valueOf(System.currentTimeMillis() / 1000));
                        }
                        
                        // 设置inspections
                        if (productInfo.get(4) instanceof List) {
                            List<?> inspections = (List<?>) productInfo.get(4);
                            List<String> inspectionStrings = new ArrayList<>();
                            for (Object inspection : inspections) {
                                if (inspection != null) {
                                    inspectionStrings.add(inspection.toString());
                                }
                            }
                            productDTO.setInspections(inspectionStrings);
                        } else if (productInfo.get(4) != null) {
                            productDTO.setInspections(Arrays.asList(productInfo.get(4).toString()));
                        } else {
                            productDTO.setInspections(new ArrayList<>());
                        }
                        
                        // 设置owner
                        if (productInfo.get(5) != null) {
                            if (productInfo.get(5) instanceof String) {
                                productDTO.setOwner((String) productInfo.get(5));
                            } else if (productInfo.get(5) instanceof List) {
                                productDTO.setOwner(String.join(", ", (List<String>) productInfo.get(5)));
                            } else {
                                productDTO.setOwner(productInfo.get(5).toString());
                            }
                        } else {
                            productDTO.setOwner("");
                        }
                        
                        // 设置isDeleted
                        if (productInfo.get(6) instanceof Boolean) {
                            productDTO.setIsDeleted((Boolean) productInfo.get(6));
                        } else if (productInfo.get(6) instanceof String) {
                            productDTO.setIsDeleted(Boolean.parseBoolean((String) productInfo.get(6)));
                        } else {
                            productDTO.setIsDeleted(false);
                        }
                        
                        System.out.println("成功构建产品对象: " + productDTO.getId());
                        return CommonResponse.ok(productDTO);
                    } catch (Exception e) {
                        System.err.println("处理产品数据时出错: " + e.getMessage());
                        e.printStackTrace();
                        return CommonResponse.fail("F002", e);
                    }
                } else {
                    System.err.println("产品数据不完整，字段数量: " + productInfo.size());
                    return CommonResponse.fail("F002", new Exception("产品数据不完整"));
                }
            } else {
                System.err.println("未能获取产品数据或格式不正确: " + response.getReturnObject());
                return CommonResponse.fail("F002", new Exception("产品数据格式不正确"));
            }
        } catch (Exception e) {
            System.err.println("获取产品失败: " + e.getMessage());
            e.printStackTrace();
            return CommonResponse.fail("F002", e);
        }
    }

    /**
     * 获取所有产品ID
     * @return 产品ID列表
     */
    @GetMapping
    public CommonResponse getAllProducts() {
        try {
            CallResponse response = agriculturalTraceabilityService.getAllProductIds();
            return CommonResponse.ok(response.getReturnObject());
        } catch (Exception e) {
            return CommonResponse.fail("F003", e);
        }
    }
    
    /**
     * 获取所有产品ID (专门为前端/list路径提供的端点)
     * @return 产品ID列表
     */
    @GetMapping("/list")
    public CommonResponse getProductsList() {
        try {
            // 获取所有产品ID
            CallResponse idsResponse = agriculturalTraceabilityService.getAllProductIds();
            List<String> productIds = new ArrayList<>();
            
            // 处理返回的产品ID - 记录原始返回内容以便调试
            System.out.println("原始产品ID响应: " + idsResponse.getReturnObject());
            
            // 处理不同格式的返回值
            if (idsResponse.getReturnObject() instanceof List) {
                List<?> rawIds = (List<?>) idsResponse.getReturnObject();
                System.out.println("产品原始列表: " + rawIds);
                
                for (Object item : rawIds) {
                    if (item instanceof List) {
                        // 处理嵌套列表情况
                        List<?> nestedList = (List<?>) item;
                        // 遍历嵌套列表中的所有元素
                        for (Object element : nestedList) {
                            if (element != null && !element.toString().trim().isEmpty()) {
                                String id = element.toString().trim();
                                if (!productIds.contains(id)) {  // 避免重复
                                    productIds.add(id);
                                    System.out.println("添加产品ID: " + id);
                                }
                            }
                        }
                    } else if (item instanceof String) {
                        String id = ((String) item).trim();
                        if (!id.isEmpty() && !productIds.contains(id)) {
                            productIds.add(id);
                            System.out.println("添加产品ID: " + id);
                        }
                    } else if (item != null) {
                        String id = item.toString().trim();
                        if (!id.isEmpty() && !productIds.contains(id)) {
                            productIds.add(id);
                            System.out.println("添加产品ID: " + id);
                        }
                    }
                }
            } else if (idsResponse.getReturnObject() != null) {
                String id = idsResponse.getReturnObject().toString().trim();
                if (!id.isEmpty()) {
                    productIds.add(id);
                    System.out.println("添加产品ID: " + id);
                }
            }
            
            System.out.println("解析后的产品ID列表: " + productIds);
            
            // 如果没有产品，返回空列表
            if (productIds.isEmpty()) {
                System.out.println("未找到任何产品ID");
                return CommonResponse.ok(new ArrayList<>());
            }
            
            // 获取每个产品的详细信息
            List<ProductDTO> products = new ArrayList<>();
            for (String id : productIds) {
                try {
                    System.out.println("正在获取产品详情: " + id);
                    AgriculturalTraceabilityGetProductInputBO inputBO = new AgriculturalTraceabilityGetProductInputBO();
                    inputBO.set_id(id);
                    
                    CallResponse productResponse = agriculturalTraceabilityService.getProduct(inputBO);
                    System.out.println("产品 " + id + " 响应: " + productResponse.getReturnObject());
                    
                    if (productResponse.getReturnObject() instanceof List) {
                        List<Object> productInfo = (List<Object>) productResponse.getReturnObject();
                        if (productInfo.size() >= 7) {
                            ProductDTO productDTO = new ProductDTO();
                            productDTO.setId(id);
                            productDTO.setName(productInfo.get(0) != null ? productInfo.get(0).toString() : id);
                            productDTO.setProducer(productInfo.get(1) != null ? productInfo.get(1).toString() : "未知");
                            productDTO.setOrigin(productInfo.get(2) != null ? productInfo.get(2).toString() : "未知");
                            
                            // 处理生产日期
                            if (productInfo.get(3) != null) {
                                try {
                                    if (productInfo.get(3) instanceof BigInteger) {
                                        productDTO.setProductionDate((BigInteger) productInfo.get(3));
                                    } else {
                                        productDTO.setProductionDate(new BigInteger(productInfo.get(3).toString()));
                                    }
                                } catch (Exception e) {
                                    System.err.println("处理产品 " + id + " 的生产日期时出错: " + e.getMessage());
                                    productDTO.setProductionDate(BigInteger.ZERO);
                                }
                            }
                            
                            // 处理检验记录
                            if (productInfo.get(4) instanceof List) {
                                productDTO.setInspections((List<String>) productInfo.get(4));
                            } else {
                                productDTO.setInspections(new ArrayList<>());
                            }
                            
                            // 处理所有者
                            productDTO.setOwner(productInfo.get(5) != null ? productInfo.get(5).toString() : "");
                            
                            // 处理删除状态
                            if (productInfo.get(6) instanceof Boolean) {
                                productDTO.setIsDeleted((Boolean) productInfo.get(6));
                            } else {
                                productDTO.setIsDeleted(false);
                            }
                            
                            // 只添加未删除的产品
                            if (!productDTO.getIsDeleted()) {
                                products.add(productDTO);
                                System.out.println("成功添加产品: " + productDTO.getId());
                            } else {
                                System.out.println("跳过已删除的产品: " + productDTO.getId());
                            }
                        } else {
                            System.out.println("产品 " + id + " 数据不完整，跳过");
                        }
                    }
                } catch (Exception e) {
                    System.err.println("处理产品 " + id + " 时出错: " + e.getMessage());
                }
            }
            
            System.out.println("最终返回的产品数量: " + products.size());
            return CommonResponse.ok(products);
        } catch (Exception e) {
            System.err.println("获取产品列表时出错: " + e.getMessage());
            e.printStackTrace();
            return CommonResponse.fail("F003", e);
        }
    }

    /**
     * 更新产品信息
     * @param request 产品请求
     * @return 更新结果
     */
    @PutMapping
    public CommonResponse updateProduct(@RequestBody ProductRequest request) {
        try {
            AgriculturalTraceabilityUpdateProductInfoInputBO inputBO = new AgriculturalTraceabilityUpdateProductInfoInputBO();
            inputBO.set_id(request.getId());
            inputBO.set_field(request.getField());
            inputBO.set_value(request.getValue());
            
            TransactionResponse response = agriculturalTraceabilityService.updateProductInfo(inputBO);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("F004", e);
        }
    }

    /**
     * 添加检验记录
     * @param request 产品请求
     * @return 添加结果
     */
    @PostMapping("/inspection")
    public CommonResponse addInspection(@RequestBody ProductRequest request) {
        try {
            AgriculturalTraceabilityAddInspectionInputBO inputBO = new AgriculturalTraceabilityAddInspectionInputBO();
            inputBO.set_id(request.getId());
            inputBO.set_inspectionInfo(request.getInspectionInfo());
            
            TransactionResponse response = agriculturalTraceabilityService.addInspection(inputBO);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("F005", e);
        }
    }

    /**
     * 购买产品
     * @param request 产品请求
     * @return 购买结果
     */
    @PostMapping("/purchase")
    public CommonResponse purchaseProduct(@RequestBody ProductRequest request) {
        try {
            AgriculturalTraceabilityPurchaseProductInputBO inputBO = new AgriculturalTraceabilityPurchaseProductInputBO();
            inputBO.set_id(request.getId());
            inputBO.set_buyer(request.getBuyerAddress());
            
            TransactionResponse response = agriculturalTraceabilityService.purchaseProduct(inputBO);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("F006", e);
        }
    }

    /**
     * 删除产品
     * @param request 产品请求
     * @return 删除结果
     */
    @DeleteMapping
    public CommonResponse deleteProduct(@RequestBody ProductRequest request) {
        try {
            AgriculturalTraceabilityDeleteProductInputBO inputBO = new AgriculturalTraceabilityDeleteProductInputBO();
            inputBO.set_id(request.getId());
            inputBO.set_reason(request.getReason());
            
            TransactionResponse response = agriculturalTraceabilityService.deleteProduct(inputBO);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("F007", e);
        }
    }

    /**
     * 恢复已删除产品
     * @param id 产品ID
     * @return 恢复结果
     */
    @PostMapping("/restore/{id}")
    public CommonResponse restoreProduct(@PathVariable String id) {
        try {
            AgriculturalTraceabilityRestoreProductInputBO inputBO = new AgriculturalTraceabilityRestoreProductInputBO();
            inputBO.set_id(id);
            
            TransactionResponse response = agriculturalTraceabilityService.restoreProduct(inputBO);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("F008", e);
        }
    }

    /**
     * 验证数据完整性
     * @param request 产品请求
     * @return 验证结果
     */
    @PostMapping("/verify")
    public CommonResponse verifyDataIntegrity(@RequestBody ProductRequest request) {
        try {
            AgriculturalTraceabilityVerifyDataIntegrityInputBO inputBO = new AgriculturalTraceabilityVerifyDataIntegrityInputBO();
            inputBO.set_id(request.getId());
            inputBO.set_name(request.getName());
            inputBO.set_producer(request.getProducer());
            inputBO.set_productionDate(request.getProductionDate());
            inputBO.set_origin(request.getOrigin());
            
            CallResponse response = agriculturalTraceabilityService.verifyDataIntegrity(inputBO);
            return CommonResponse.ok(response.getReturnObject());
        } catch (Exception e) {
            return CommonResponse.fail("F009", e);
        }
    }
} 